package com.alienwarp.imageprocess;

import java.util.Arrays;

import org.eclipse.swt.graphics.ImageData;

public class ImageProcessor
{
	/*
	 * Image mean filter.
	 * Input:
	 *      srcImage: input image data.
	 *      winWidth: Filter width.
	 *      winHeight: Filter height.
	 *      
	 * Output:
	 *      processed image.
	 */
	public static ImageData imageMeanFilter(ImageData srcImage, int winWidth, int winHeight)
	{
		int bytesPerPixel = srcImage.bytesPerLine / srcImage.width;
		byte[] newData = new byte[srcImage.data.length];
		Arrays.fill(newData, (byte)0);  //Initialize
		
		int halfWinWidth = winWidth/2;
		int halfWinHeight = winHeight/2;
		int nWinPixels = (halfWinWidth * 2 + 1) * (halfWinHeight * 2 + 1);
		
		long[] temp = new long[bytesPerPixel];
		Arrays.fill(temp, 0);

		//The edge is not processed here.
		for(int y = halfWinHeight; y < srcImage.height - halfWinHeight; y++)
			for(int x = halfWinWidth; x < srcImage.width - halfWinWidth; x++)
			{
				//loop around the neighbor region
				for(int yIndex = - halfWinHeight; yIndex <= halfWinHeight; yIndex++)
					for(int xIndex = -halfWinWidth; xIndex <= halfWinWidth; xIndex++)
					{
						//for RGBA image you must process every color channel
						for(int iByte = 0; iByte < bytesPerPixel; iByte++)
						{
							//Notice: here 0xFF & byte convert the data to unsigned byte.
							temp[iByte] += 0xFF & srcImage.data[(y + yIndex) * srcImage.bytesPerLine + (x + xIndex) * bytesPerPixel + iByte];
						}
					}
				
				//Calculate the mean value.
				for(int iByte = 0; iByte < bytesPerPixel; iByte++)
				{
					newData[y * srcImage.bytesPerLine + x * bytesPerPixel + iByte] = (byte)(temp[iByte] / nWinPixels);
					temp[iByte] = 0;
				}
			}
		
		ImageData newImageData = new ImageData(srcImage.width, srcImage.height, 
				srcImage.depth, srcImage.palette, srcImage.bytesPerLine, newData);
		newImageData.transparentPixel = srcImage.transparentPixel;
				
		return newImageData;
	}
}
